import 'dart:convert';

import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/utils/media_recorder_util.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/views/stream/dialog/anchor_select_list_bottom_sheet.dart';
import 'package:star_author/views/stream/dialog/beauty_dialog.dart';
import 'package:star_author/views/stream/mute_list_page.dart';
import 'package:star_author/widgets/custom_image/custom_image.dart';
import 'package:star_author/widgets/empty_view/h_empty_view.dart';
import 'package:star_author/widgets/empty_view/v_empty_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';

import '../../../config/base_configuration.dart';
import '../../../utils/common_util/toast/custom_toast.dart';
import '../../../utils/http/http_util.dart';
import '../local_video_page.dart';
import 'live_detection_info.dart';

class LiveManagement extends StatefulWidget {
  Function? leave;
  late final RtcEngine? engine;
  bool isMute = false;
  Function? muteCallBack;
  final Map studioDetailMap;
  final Function? selectAnchorCallback;

  LiveManagement({
    Key? key,
    this.leave,
    this.engine,
    this.isMute: false,
    this.muteCallBack,
    required this.studioDetailMap,
    this.selectAnchorCallback,
  }) : super(key: key);

  @override
  State<LiveManagement> createState() => _LiveManagementState();
}

class _LiveManagementState extends State<LiveManagement> {
  List tabs = [
    {'label': '禁言名单', 'icon': 'ic_mute_lt'},
    {'label': '本地视频', 'icon': 'ic_local_video_lt'}
  ];

  getList() async {
    ///api/v1/studios/{id}/banned_user_list
    List fileList = await MediaRecorderUtil.getFileList();
    if (mounted) {
      setState(() {
        tabs[1]['count'] = fileList.length.toString();
      });
    }
    await HttpUtil.commonRequest(Get.context!,
            "/api/v1/studios/${StreamConf.liveId}/banned_user_list",
            isErrorToast: false, isCatchErrorLogin: false, isLoading: false)
        .then((value) {
      if (mounted) {
        setState(() {
          list = value.data['data'] ?? [];
          tabs[0]['count'] = list.length.toString();
        });
      }
    });
  }

  List list = [];

  Map? selectAnchorDetailMap;

  Map studioDetailMap = {};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.studioDetailMap['living_anchor'] != null) {
      selectAnchorDetailMap = widget.studioDetailMap['living_anchor'];
    }
    studioDetailMap = widget.studioDetailMap;

    getList();
  }

  @override
  void didUpdateWidget(covariant LiveManagement oldWidget) {
    setState(() {});
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        minHeight: 320.w,
        maxHeight: 390.w,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(12.w),
          topRight: Radius.circular(12.w),
        ),
      ),
      child: Stack(
        children: [
          Positioned(
            child: GestureDetector(
              child: Container(
                alignment: Alignment.topRight,
                child: RoucesUtil.getAssetsIcon('lt_common/clear', 14.w),
                padding: EdgeInsets.only(
                  left: 12.w,
                  right: 12.w,
                  top: 10.w,
                ),
              ),
              onTap: () {
                Get.back();
              },
              behavior: HitTestBehavior.opaque,
            ),
          ),
          Container(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  alignment: Alignment.center,
                  child: Text(
                    "直播管理",
                    style: TextStyle(
                        fontSize: 16.sp,
                        color: Color(0xFF333333),
                        fontWeight: FontWeight.w500),
                  ),
                  margin: EdgeInsets.only(left: 12.w, bottom: 24.w, top: 25.w),
                ),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    if (studioDetailMap['select_anchors_list'] == null) {
                      CustomToast.show("该直播间未绑定讲解人列表");
                      return;
                    }

                    Get.bottomSheet(
                      AnchorSelectListBottomSheet(
                        studioDetailMap,
                        (val) {
                          onChangeAnchor(val);
                        },
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.vertical(
                          top: Radius.circular(16.w),
                        ),
                      ),
                      barrierColor: Colors.transparent,
                      isScrollControlled: true,
                    );
                  },
                  child: Container(
                    width: 350.w,
                    height: 60.w,
                    decoration: BoxDecoration(
                      color: UIConstant.colorF6F6,
                      borderRadius: BorderRadius.all(
                        Radius.circular(8.w),
                      ),
                    ),
                    padding: EdgeInsets.symmetric(horizontal: 12.w),
                    child: selectAnchorDetailMap == null
                        ? Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "暂无讲解的主播",
                                style: TextStyle(
                                  color: UIConstant.color99,
                                  fontSize: 14.sp,
                                ),
                              ),
                              Row(
                                children: [
                                  Text(
                                    '选择主播',
                                    style: TextStyle(
                                        fontSize: 14.sp,
                                        color: UIConstant.color33),
                                  ),
                                  SizedBox(
                                    width: 10.w,
                                  ),
                                  Image.asset('images/lt_common/right_arrow.png',
                                      height: 9.w),
                                ],
                              )
                            ],
                          )
                        : Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              CustomImage.loadAvatarUrl(
                                "${selectAnchorDetailMap!['avatar']}",
                                width: 24.w,
                              ),
                              HEmptyView(8.w),
                              Container(
                                width: 70.w,
                                child: Text(
                                  "${selectAnchorDetailMap!['nickname']}",
                                  style: TextStyle(
                                    color: UIConstant.color33,
                                    fontSize: 14.sp,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              Container(
                                width: 28.w,
                                height: 12.w,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(2.w),
                                    ),
                                    color: Color(0xffFEBA07)),
                                alignment: Alignment.center,
                                child: Text(
                                  "直播中",
                                  style: TextStyle(
                                    fontSize: 8.sp,
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: Container(),
                                flex: 1,
                              ),
                              Text(
                                '切换主播',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: UIConstant.color99,
                                ),
                              ),
                              SizedBox(
                                width: 10.w,
                              ),
                              Image.asset(
                                'images/lt_common/right_arrow.png',
                                height: 9.w,
                              ),
                            ],
                          ),
                  ),
                ),
                VEmptyView(10.w),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ...List.generate(tabs.length, (index) {
                      return GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          height: 60.w,
                          width: 170.w,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  SizedBox(
                                    width: 20.w,
                                  ),
                                  RoucesUtil.getAssetsIcon(
                                      tabs[index]['icon'] ?? '', 20.w),
                                  SizedBox(
                                    width: 14.w,
                                  ),
                                  Text(
                                    tabs[index]['label'] ?? "",
                                    style: TextStyle(
                                        fontSize: 14.sp,
                                        color: UIConstant.color33),
                                  )
                                ],
                              ),
                              Row(
                                children: [
                                  Text(
                                    tabs[index]['count'] ?? "0",
                                    style: TextStyle(
                                        fontSize: 14.sp,
                                        color: UIConstant.color33),
                                  ),
                                  SizedBox(
                                    width: 10.w,
                                  ),
                                  Image.asset('images/lt_common/right_arrow.png',
                                      height: 9.w),
                                  SizedBox(
                                    width: 10.w,
                                  ),
                                ],
                              )
                            ],
                          ),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8.w),
                              color: Color(0xFFF6F6F6)),
                          margin: EdgeInsets.symmetric(
                            horizontal: 5.w,
                          ),
                        ),
                        onTap: () {
                          if (tabs[index]['label'] == "禁言名单") {
                            Get.to(MuteListPage(), preventDuplicates: false)!
                                .then((value) {
                              getList();
                            });
                          } else if (tabs[index]['label'] == "本地视频") {
                            Get.to(LocalVideoPage(), preventDuplicates: false)!
                                .then((value) {
                              getList();
                            });
                          }
                        },
                      );
                    }),
                  ],
                ),
                Container(
                  width: Get.width - 24.w,
                  margin: EdgeInsets.only(
                    top: 20.w,
                    bottom: 10.w,
                  ),
                  child: Row(
                    children: [
                      GestureDetector(
                        child: Container(
                          height: 60.w,
                          width: 170.w,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  SizedBox(
                                    width: 20.w,
                                  ),
                                  RoucesUtil.getAssetsIcon(
                                      widget.isMute
                                          ? 'ic_live_mute_lt'
                                          : 'ic_live_not_mute_lt',
                                      22.w),
                                  SizedBox(
                                    width: 14.w,
                                  ),
                                  Text(
                                    widget.isMute ? "解除静音" : "直播间静音",
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: widget.isMute
                                          ? Color(0xFFE02020)
                                          : UIConstant.color33,
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(),
                            ],
                          ),
                          margin: EdgeInsets.only(
                            right: 5.w,
                          ),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8.w),
                            color: Color(0xFFF6F6F6),
                          ),
                        ),
                        onTap: () {
                          widget.engine?.muteLocalAudioStream(!widget.isMute);
                          setState(() {
                            widget.isMute = !widget.isMute;
                            widget.muteCallBack!(widget.isMute);
                          });
                        },
                      ),
                      Expanded(
                        child: GestureDetector(
                          child: Container(
                            height: 60.w,
                            width: 170.w,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    SizedBox(
                                      width: 20.w,
                                    ),
                                    RoucesUtil.getAssetsIcon(
                                        'ic_mei_hua_lt', 23.w),
                                    SizedBox(
                                      width: 14.w,
                                    ),
                                    Text(
                                      "直播美化",
                                      style: TextStyle(
                                        fontSize: 14.sp,
                                        color: UIConstant.color33,
                                      ),
                                    ),
                                  ],
                                ),
                                Container(
                                  child: Image.asset(
                                    'images/lt_common/right_arrow.png',
                                    height: 9.w,
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                            ),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8.w),
                                color: Color(0xFFF6F6F6)),
                            margin: EdgeInsets.only(
                              left: 5.w,
                            ),
                          ),
                          onTap: () {
                            Get.back();
                            Get.bottomSheet(
                              BeautyDialog(
                                engine: widget.engine!,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.vertical(
                                  top: Radius.circular(16.w),
                                ),
                              ),
                              //不需要黑色遮罩层
                              barrierColor: Colors.transparent,
                              isScrollControlled: true, persistent: false,
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: Get.width - 24.w,
                  child: Row(
                    children: [
                      GestureDetector(
                        child: Container(
                          height: 60.w,
                          width: 170.w,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  SizedBox(
                                    width: 20.w,
                                  ),
                                  RoucesUtil.getAssetsIcon(
                                      'ic_live_info_lt', 23.w),
                                  SizedBox(
                                    width: 14.w,
                                  ),
                                  Text(
                                    "直播监测信息",
                                    style: TextStyle(
                                        fontSize: 14.sp,
                                        color: Color(0xFFE02020)),
                                  ),
                                ],
                              ),
                              Container(
                                margin: EdgeInsets.only(
                                  right: 10.w,
                                ),
                                child: Image.asset(
                                    'images/lt_common/right_arrow.png',
                                    height: 9.w),
                              ),
                            ],
                          ),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8.w),
                              color: Color(0xFFF6F6F6)),
                          margin: EdgeInsets.only(
                            right: 5.w,
                          ),
                        ),
                        onTap: () {
                          Get.to(
                              LiveDetectionInfo(
                                engine: widget.engine,
                              ),
                              preventDuplicates: false);
                        },
                      ),
                      GestureDetector(
                        child: Container(
                          height: 60.w,
                          width: 170.w,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              RoucesUtil.getAssetsIcon('offline_lt', 23.w),
                              SizedBox(
                                width: 14.w,
                              ),
                              Text(
                                "关闭直播间",
                                style: TextStyle(
                                    fontSize: 14.sp, color: Colors.white),
                              ),
                            ],
                          ),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8.w),
                            color: Color(0xFFF04529),
                          ),
                          margin: EdgeInsets.only(
                            left: 5.w,
                          ),
                        ),
                        onTap: () {
                          widget.leave!();
                        },
                      ),
                    ],
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  uBand(index, id) {
    HttpUtil.commonRequest(
        Get.context!, "/api/v1/studios/${StreamConf.liveId}/unban_user",
        method: HttpUtil.MethodPost, data: {"user_id": id}).then((value) {
      if (value.statusCode == 200) {
        getList();
        CustomToast.show("取消禁言成功");
      }
    });
  }

  void onChangeAnchor(map) {
    HttpUtil.commonRequest(
      Get.context!,
      "/api/v1/studios/${studioDetailMap['id'] ?? ''}/change_anchor/${map['id'] ?? ''}",
      isLoading: true,
      method: HttpUtil.MethodPut,
    ).then((value) async {
      if (value.statusCode == 201) {
        CustomToast.show("切换讲解主播成功");
        sendChangeAnchorMessage();
        selectAnchorDetailMap = map;
        if (mounted) setState(() {});

        HttpUtil.commonRequest(
                Get.context!, '/api/v1/studios/${StreamConf.liveId}')
            .then((value) {
          studioDetailMap = value.data;
          if (widget.selectAnchorCallback != null) {
            widget.selectAnchorCallback!(studioDetailMap);
          }
          if (mounted) setState(() {});
        });
      }
    });
  }

  ///直播间发送切换讲解人通知
  Future<Message?> sendChangeAnchorMessage() async {
    TextMessage txtMessage = new TextMessage();
    Map map = {'operation': OperationKey.change_anchor, 'data': {}};
    txtMessage.extra = json.encode(map);
    Message? msg = await RongIMClient.sendMessage(
        RCConversationType.ChatRoom, StreamConf.channelKey, txtMessage);

    return msg;
  }
}
